﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace MetaSharp.Transformation.Patterns
{
    class ArrayPattern : Pattern
    {
        public Pattern Pattern { get; private set; }
        public ArrayPattern(Pattern pattern)
            : base(PatternKind.Array)
        {
            this.Pattern = pattern;
        }

        public override PatternMatch Compile()
        {
            var p = Pattern.Compile();
            return s => Target(s, p);
        }

        private static async Task<IMatch> Target(IScope scope, PatternMatch pattern)
        {
            if (!scope.Stream.IsEmpty)
            {
                var next = scope.Stream.Next();
                var into = next.Into();
                if (into != null)
                {
                    var match = await pattern(scope.SetStream(into));
                    if (match.Matched && match.End.Stream.IsEmpty)
                    {
                        return match.SetEnd(match.End.SetStream(next));
                    }
                }
            }

            return await Transformation.Match.Fail(scope);
        }
    }
}
